//
//  SVTopScrollView.m
//  SlideView
//
//  Created by Chen Yaoqiang on 13-12-27.
//  Copyright (c) 2013年 Chen Yaoqiang. All rights reserved.
//

#import "SVTopScrollView.h"
#import "SliderView-Prefix.pch"


//按钮空隙
#define BUTTONGAP 5
//滑条宽度
#define CONTENTSIZEX 330

//按钮id
#define BUTTONID (sender.tag-100)
//滑动id
#define BUTTONSELECTEDID (scrollViewSelectedChannelID - 100)


@implementation SVTopScrollView

//@synthesize  功能：让编译器自动编写一个与数据成员同名的方法声明来省去读写方法的声明
@synthesize nameArray;
@synthesize scrollViewSelectedChannelID;
@synthesize userSelectdButtonTag;
@synthesize buttonOriginXArray;
@synthesize buttonWithArray;
//
+ (SVTopScrollView *)shareInstance {
    static SVTopScrollView *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance=[[self alloc] initWithFrame:CGRectMake(10, IOS7_STATUS_BAR_HEGHT, CONTENTSIZEX, 44)];
    });
    
    
    return _instance;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //滑动协议 设置代理人
        self.delegate = self;
        self.backgroundColor = [UIColor clearColor];
        //整页滑动
        self.pagingEnabled = YES;
//        self.userInteractionEnabled = YES;
        //取消底部的滑动条
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        
        userSelectedChannelID = 100;
        scrollViewSelectedChannelID = 100;
        
        //初始化可变数组
        self.buttonOriginXArray = [NSMutableArray array];
        self.buttonWithArray = [NSMutableArray array];
    }
    return self;
}

- (void)initWithNameButtons:(UICollectionView *)collectionView
{
    
    self.collect = collectionView;
//    userSelectedChannelID = self.collect.contentOffset.x;
    //与按钮空隙数值相同
    float xPos = 5;
    //for循环添加button
    for (int i = 0; i < [self.nameArray count]; i++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *title = [self.nameArray objectAtIndex:i];
      //没添加一个按钮 添加一个tag值
        [button setTag:i+100];
        
        
        //判断第一个按钮的状态
        if (i == 0) {
            button.selected = YES;
        }
        
        [button setTitle:title forState:UIControlStateNormal];
       
        //常态颜色为灰色
        [button setTitleColor:[SVGloble colorFromHexRGB:@"868686"] forState:UIControlStateNormal];
        //选中颜色为红色
        [button setTitleColor:[SVGloble colorFromHexRGB:@"bb0b15"] forState:UIControlStateSelected];
        
        //添加button的点击事件
        [button addTarget:self action:@selector(selectNameButton:) forControlEvents:UIControlEventTouchUpInside];
      
//int buttonWidth = [title sizeWithFont:button.titleLabel.font
//                            constrainedToSize:CGSizeMake(0, 30)
//                                lineBreakMode:NSLineBreakByClipping].width;
        
        //设置按钮字体大小
//        button.titleLabel.font = [UIFont systemFontOfSize:20.0];
        //设置段落模式
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.alignment = NSLineBreakByWordWrapping;
        NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:25], NSParagraphStyleAttributeName: paragraph};
        
        CGSize buttonWidth = [title boundingRectWithSize:CGSizeMake(0, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil].size;
        
        
        button.frame = CGRectMake(xPos, 9, buttonWidth.width+BUTTONGAP, 30);
//        @(xPos)将xPos转换成NSNumber类型
        [buttonOriginXArray addObject:@(xPos)];
        //按钮的x坐标
        xPos += buttonWidth.width+BUTTONGAP;
        //每个按钮的宽度 添加到数组中
        [buttonWithArray addObject:@(button.frame.size.width)];
        //button添加到scrollView上
        [self addSubview:button];
    }
    
//    NSInteger  a = (NSInteger)(self.collect.contentOffset.x )/ 375;
        //scrollView的偏移量
        self.contentSize = CGSizeMake(xPos, 44);
        //红色横条坐标
        shadowImageView = [[UIImageView alloc] initWithFrame:CGRectMake(BUTTONGAP, 0, [[buttonWithArray objectAtIndex:0] floatValue], 44)];
        [shadowImageView setImage:[UIImage imageNamed:@"red_line_and_shadow.png"]];
        [self addSubview:shadowImageView];

  
    
    
}

//点击顶部条滚动标签
- (void)selectNameButton:(UIButton *)sender
{
    [self adjustScrollViewContentX:sender];
        //如果更换按钮
    if (sender.tag != userSelectedChannelID) {
        //取之前的按钮
        //通过tag值获取之前的按钮
        UIButton *lastButton = (UIButton *)[self viewWithTag:userSelectedChannelID];
        //设置状态为no
        lastButton.selected = NO;
        //赋值按钮ID
        userSelectedChannelID = sender.tag;
   }
    //按钮与页面关联
    //按钮选中状态
    if (!sender.selected) {
        sender.selected = YES;
       [UIView animateWithDuration:0.25 animations:^{
            //红条图片滚到对应的button位置
//           buttonWithArray objectAtIndex:BUTTONID 取button所在数组下标的button的宽度
            [shadowImageView setFrame:CGRectMake(sender.frame.origin.x, 0, [[buttonWithArray objectAtIndex:BUTTONID] floatValue], 44)];
            
        } completion:^(BOOL finished) {
            if (finished) {
////                设置下一页出现
//                //获取collectionView
              self.collect.contentOffset = CGPointMake((userSelectedChannelID - 100) * self.collect.frame.size.width, 0);
//                //赋值滑动列表选择频道ID
                scrollViewSelectedChannelID = sender.tag;
            }
        }];
    
    }
    //重复点击选中按钮
    else {
        
    }
}
//调整滚动按钮显示
- (void)adjustScrollViewContentX:(UIButton *)sender
{
    float originX = [[buttonOriginXArray objectAtIndex:BUTTONID] floatValue];
    float width = [[buttonWithArray objectAtIndex:BUTTONID] floatValue];
    //判断点击的是当前按钮的前面还是后面 并作出相应的偏移
    if (sender.frame.origin.x - self.contentOffset.x > CONTENTSIZEX-(BUTTONGAP+width)) {
        [self setContentOffset:CGPointMake(originX - 30, 0)  animated:YES];
    }
    
    if (sender.frame.origin.x - self.contentOffset.x < BUTTONGAP) {
        [self setContentOffset:CGPointMake(originX,0)  animated:YES];
    }
}

//滚动内容页顶部滚动
- (void)setButtonUnSelect
{
    //滑动撤销选中按钮
    UIButton *lastButton = (UIButton *)[self viewWithTag:scrollViewSelectedChannelID];
    lastButton.selected = NO;
}

- (void)setButtonSelect
{
    //滑动选中按钮
    UIButton *button = (UIButton *)[self viewWithTag:scrollViewSelectedChannelID];
    //参数1:动画持续事件
    [UIView animateWithDuration:0.25 animations:^{
        
        [shadowImageView setFrame:CGRectMake(button.frame.origin.x, 0, [[buttonWithArray objectAtIndex:button.tag-100] floatValue], 44)];
        
    } completion:^(BOOL finished) {
        if (finished) {
            if (!button.selected) {
                button.selected = YES;
                userSelectedChannelID = button.tag;
            }
        }
    }];
    
}

-(void)setScrollViewContentOffset
{
    float originX = [[buttonOriginXArray objectAtIndex:BUTTONSELECTEDID] floatValue];
    float width = [[buttonWithArray objectAtIndex:BUTTONSELECTEDID] floatValue];
    
    if (originX - self.contentOffset.x > CONTENTSIZEX-(BUTTONGAP+width)) {
        [self setContentOffset:CGPointMake(originX - 30, 0)  animated:YES];
    }
    
    if (originX - self.contentOffset.x < 5) {
        [self setContentOffset:CGPointMake(originX,0)  animated:YES];
    }
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
